<template>
    <div class="visitor-appointment">
        <!-- 头部导航栏 -->
        <van-nav-bar title="访客预约" left-arrow @click-left="$router.push('/')" class="nav-bar" />

        <!-- 访客照片上传 -->
        <div class="photo-upload">
            <h3>访客照片</h3>
            <div style="text-align: center;">
                <van-uploader v-model="fileList" :max-count="1" :after-read="afterRead">
                    <div class="upload-area">
                        <van-icon name="plus" size="24" />
                        <span>上传头像</span>
                    </div>
                </van-uploader>
            </div>

        </div>

        <!-- 被访人信息 -->
        <div class="form-section">
            <h3>被访人信息</h3>
            <van-form>
                <van-field v-model="selectedHostName" name="hostName" label="被访人" placeholder="请选择被访人" readonly
                    @click="showHostPicker = true" :rules="[{ required: true, message: '请选择被访人' }]" />
            </van-form>
        </div>

        <!-- 被访人选择器弹窗 -->
        <van-popup v-model:show="showHostPicker" position="bottom" round :style="{ height: '80%' }">
            <van-nav-bar title="选择被访人" left-text="取消" right-text="确定" 
                @click-left="showHostPicker = false" @click-right="handleHostConfirm" />
            <div class="picker-container">
                <!-- 左侧部门树 -->
                <van-tree-select v-model:active-id="activeDeptId" v-model:main-active-index="mainActiveIndex"
                    :items="deptTree" class="dept-tree" />
                <!-- 右侧人员列表 -->
                <div class="user-list">
                    <van-radio-group v-model="selectedHostId">
                        <template v-if="currentDeptUsers.length > 0">
                            <van-cell v-for="user in currentDeptUsers" :key="user.id" :title="user.name"
                                :label="user.phone" clickable @click="selectedHostId = user.id">
                                <template #right-icon>
                                    <van-radio :name="user.id" />
                                </template>
                            </van-cell>
                        </template>
                        <van-empty v-else description="该部门暂无人员" />
                    </van-radio-group>
                </div>
            </div>
        </van-popup>

        <!-- 访客信息 -->
        <div class="form-section">
            <h3>访客信息</h3>
            <van-form @submit="onSubmit">
                <van-field class="custom-field" v-model="visitorName" name="visitorName" label="姓名"
                    placeholder="请输入访客姓名" :rules="[{ required: true, message: '请输入访客姓名' }]" />
                <van-field v-model="visitorPhone" name="visitorPhone" label="手机号" placeholder="请输入访客手机号"
                    :rules="[{ required: true, message: '请输入访客手机号' }]" />
                <van-field v-model="company" name="company" label="公司" placeholder="请输入访客公司"
                    :rules="[{ required: true, message: '请输入访客公司' }]" />
                <van-field v-model="purpose" name="purpose" label="来访目的" placeholder="请选择来访目的" readonly
                    @click="showPurposePicker = true" :rules="[{ required: true, message: '请选择来访目的' }]" />
                <van-field v-model="visitDate" name="visitDate" label="来访时间" readonly placeholder="请选择来访日期"
                    @click="showDatePicker = true" :rules="[{ required: true, message: '请选择来访日期' }]" />

                <!-- 底部按钮 -->
                <div class="form-buttons">
                    <van-button round type="default" @click="onReset">重置</van-button>
                    <van-button round type="primary" native-type="submit">提交</van-button>
                </div>
            </van-form>
        </div>

        <!-- 日期选择器弹窗 -->
        <van-popup v-model:show="showDatePicker" position="bottom">
            <van-date-picker title="选择来访日期" :min-date="minDate" :max-date="maxDate" @confirm="onDateConfirm"
                @cancel="showDatePicker = false" />
        </van-popup>

        <!-- 来访目的选择器弹窗 -->
        <van-popup v-model:show="showPurposePicker" position="bottom">
            <van-picker :columns="purposeList" @confirm="onPurposeConfirm" @cancel="showPurposePicker = false"
                show-toolbar title="选择来访目的" />
        </van-popup>
    </div>
</template>

<script>
import { getPurposeList } from '@/api/purpose'
import { applyVisit } from '@/api/visit'
import { getDepartmentTree, getAllEmployees } from '@/api/employee'
import { showToast, showLoadingToast } from 'vant'

export default {
    name: 'VisitorAppointment',
    data() {
        return {
            fileList: [],
            selectedHostName: '',
            selectedHostId: '',
            visitorName: '',
            visitorPhone: '',
            company: '',
            purpose: '',
            visitDate: '',
            showDatePicker: false,
            showPurposePicker: false,
            showHostPicker: false,
            minDate: new Date(),
            maxDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            purposeList: [],
            deptTree: [],
            activeDeptId: null,
            mainActiveIndex: 0,
            currentDeptUsers: [],
            employeesByDept: {}
        }
    },
    created() {
        this.getPurposeList()
        this.initDeptAndEmployees()
    },
    watch: {
        activeDeptId: {
            handler(newDeptId) {
                if (newDeptId) {
                    this.updateCurrentDeptUsers()
                }
            }
        }
    },
    methods: {
        afterRead(file) {
            // 此处可以添加图片上传逻辑
            console.log('上传的文件:', file)
        },
        onDateConfirm(date) {
            // 直接使用selectedValues数组中的年月日值
            const [year, month, day] = date.selectedValues
            this.visitDate = `${year}-${month}-${day}`
            this.showDatePicker = false
        },
        async onSubmit() {
            // 提交表单逻辑
            if (!this.fileList.length) {
                showToast('请上传访客照片');
                return;
            }

            // 显示加载提示
            const loading = showLoadingToast({
                message: '提交中...',
                forbidClick: true,
                duration: 0
            });

            try {
                // 整理表单数据
                const formData = {
                    visitorName: this.visitorName,
                    visitorPhone: this.visitorPhone,
                    company: this.company,
                    purpose: this.purpose,
                    purposeId: this.purposeId,
                    visitDate: this.visitDate,
                    hostName: this.hostName,
                    hostPhone: this.hostPhone,
                    // 这里应该添加图片上传后的URL，目前只是示例
                    avatar: this.fileList.length > 0 ? this.fileList[0].content : ''
                };

                // 调用访客预约接口
                const res = await applyVisit(formData);
                
                // 关闭加载提示
                loading.close();
                
                if (res.code === 200) {
                    showToast({
                        type: 'success',
                        message: '预约申请提交成功',
                        onClose: () => {
                            // 提交成功后返回首页
                            this.$router.push('/');
                        }
                    });
                } else {
                    showToast({
                        type: 'fail',
                        message: res.message || '提交失败，请重试'
                    });
                }
            } catch (error) {
                console.error('提交访客预约失败:', error);
                loading.close();
                showToast({
                    type: 'fail',
                    message: '网络异常，请稍后重试'
                });
            }
        },
        onReset() {
            this.fileList = []
            this.hostName = ''
            this.hostPhone = ''
            this.visitorName = ''
            this.visitorPhone = ''
            this.company = ''
            this.purpose = ''
            this.visitDate = ''
        },
        async initDeptAndEmployees() {
            try {
                // 并行获取部门树和所有员工信息
                const [deptRes, employeesRes] = await Promise.all([
                    getDepartmentTree(),
                    getAllEmployees()
                ])

                if (deptRes.code === 200) {
                    this.deptTree = deptRes.data
                    console.log('部门树:', this.deptTree)
                    if (this.deptTree.length > 0) {
                        this.activeDeptId = this.deptTree[0].id
                    }
                }

                if (employeesRes.code === 200) {
                    this.employeesByDept = employeesRes.data
                    this.updateCurrentDeptUsers()
                }
            } catch (error) {
                console.error('初始化部门和员工数据失败:', error)
                showToast('数据加载失败，请重试')
            }
        },

        updateCurrentDeptUsers() {
            if (this.activeDeptId && this.employeesByDept[this.activeDeptId]) {
                this.currentDeptUsers = this.employeesByDept[this.activeDeptId]
            } else {
                this.currentDeptUsers = []
            }
        },

        handleHostConfirm() {
            const selectedUser = this.currentDeptUsers.find(user => user.id === this.selectedHostId)
            if (selectedUser) {
                this.selectedHostName = selectedUser.name
                this.hostName = selectedUser.name
                this.hostPhone = selectedUser.phone
            }
            this.showHostPicker = false
        },

        async getPurposeList() {
            try {
                const res = await getPurposeList()
                if (res.code === 200) {
                    this.purposeList = res.data.map(item => ({
                        text: item.purpose,  // 显示的文字
                        value: item.id       // 对应的值
                    }));
                }
            } catch (error) {
                console.error('获取来访目的列表失败:', error)
            }
        },
        onPurposeConfirm(value) {
            // 处理选择来访目的的逻辑
            if (value && value.selectedOptions && value.selectedOptions.length > 0) {
                const selected = value.selectedOptions[0];
                if (selected) {
                    this.purpose = selected.text;
                    this.purposeId = selected.value;
                }

                this.showPurposePicker = false;
            }
        }
    }
}
</script>

<style scoped>
.visitor-appointment {
    min-height: 100vh;
    background-color: #f7f8fa;
}


.photo-upload,
.form-section {
    background-color: #ffffff;
    margin: 12px;
    padding: 16px;
    border-radius: 8px;
}

.photo-upload h3,
.form-section h3 {
    margin: 0 0 16px;
    font-size: 16px;
    color: #323233;
}

.upload-area {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f7f8fa;
    border-radius: 8px;
}

.upload-area span {
    margin-top: 8px;
    font-size: 12px;
    color: #969799;
}

.form-buttons {
    display: flex;
    gap: 12px;
    margin-top: 24px;
    padding: 0 16px;
}

.form-buttons .van-button {
    flex: 1;
}

.picker-container {
    display: flex;
    height: calc(100vh - 46px - 50px);
}

.dept-tree {
    width: 50%;
    height: 100%;
    overflow-y: auto;
    background: #f7f8fa;
}

.dept-tree :deep(.van-tree-select__nav) {
    background-color: #f7f8fa;
}

.dept-tree :deep(.van-tree-select__nav-item) {
    color: #323233;
}

.dept-tree :deep(.van-tree-select__nav-item--active) {
    color: #1989fa;
    background-color: #ffffff;
}

.user-list {
    flex: 1;
    height: 100%;
    overflow-y: auto;
}

.custom-field {
    display: flex;
    align-items: center;
}

.custom-field .van-field__body {
    flex: 1;
}

.custom-field .van-field__error-message {
    flex-shrink: 0;
    margin-left: 10px;
    margin-top: 0;
}
</style>